<template>
   <div id="cart">
      <div id="chart-diagram" style="background-color: white; border: solid 1px #DCDFE6; width: 100%; position:relative"
      :style="{height:(mapHeight?mapHeight+'px':'100%')}">
      </div>
      <div id="infoBoxHolder"></div>
      <div class="scale-btn" v-show="treeData.length">
        <span  @click="magnifyHanle" class="magnify-btn"></span>
        <span @click="decreaseHandle" class="decrease-btn"></span>
      </div>
   </div>
</template>
<style lang="scss" scoped>
#cart{
position: relative;
}
.chart-diagram-info-content{
  border:1px solid #ddd;
  border-radius: 5px;
  padding:10px;
  background:#fff;
  width:200px;
  line-height: 30px;
  box-shadow: 5px 5px 6px #c7c5c5;
}
#chart-diagram *{
   outline: none;
   -webkit-tap-highlight-color:rgb(220, 223, 230)!important
}
.scale-btn{
   position: absolute;
   top:10px;
   left:10px;
   z-index:9999;
   span{
      width:24px;
      height:24px;
      &:hover{
         cursor: pointer;
      }
   }
}
</style>
<script>
import {getTableMapList} from "@/api/dataManagement/system/info";
import {setTypeListSelect} from "@/utils/zkComm";
import {gojsfigureColor} from "@/assets/js/fieldTypeList"
import "@/assets/js/go.js";
import "@/assets/js/button.js";
// setTypeListSelect
var $ = go.GraphObject.make;
export default {
   name: "TreeItem",
   props: {
      treeData: {
         type: Array,
         default: () => []
      },
      mapHeight: [String, Number]
   },
   data() {
      return {
         Select_Port: [],
         propsMap:[],
         linkDataArray:[],
         selectList:[],
      };
   },
   mounted() {
      var that = this;
   },
   watch:{
      treeData:{
         handler:function(newVal,oldVal){
            // this.treeDataList  = newVal;
            this.getTableMapList(newVal)
         },
         immediate: true,
         deep: true
      }
   },
   methods: {
      getTableMapList(data){
            var data = data;
            var that =this;
            var line = []
            var colorId = [];
            var colors = {
               1:'#409EFF',
               2:'#1183F8',
               3:'#67C23A',
               4:'#E6A23C',
               5:'#87CEFA',
               6:'#5F9EA0',
               7:'#00CED1',
               8:'#3CB371',
               9:'#FF00FF'
            }
            for(var i=0;i<data.length;i++){
               if(colorId.indexOf(data[i].dirId) ==-1) {
                  colorId.push(data[i].dirId)
               }
               data[i].key = data[i].tableName
               data[i].choice1 = false;
               data[i].items = new Array();
               data[i].items[0] ={'name': data[i].tableAlias,'figure': "Decision",color: gojsfigureColor.tableColor}
               data[i].items[1] ={'name': data[i].dirName,'figure': "Decision",color: "purple"}
               for(var j=0;j<data[i].relationList.length;j++){
                  line.push({'from':data[i].tableName,'to':data[i].relationList[j].refTableName,})
               }
               if(data[i].fields){
                  for(var k=0;k<data[i].fields.length;k++){
                     data[i].items.push({'name':`关联字段：${data[i].fields[k].fieldName}`,'figure': "Circle",color: gojsfigureColor.filedColor})
                  }
               }
            }
            for(var j=0;j<colorId.length;j++){
               for(var i=0;i<data.length;i++){
                  if(colorId[j] == data[i].dirId) {
                     data[i].color=colors[j+1]
                  }
               }
            }
            that.propsMap = data;
            that.linkDataArray = line;

            setTimeout(function(){
               that.goinit();
            },300)
      },
      goinit() {
      var mygoChart = document.getElementById('chart-diagram');
      var parentDiv = document.getElementById('cart');
       parentDiv.removeChild(mygoChart);
       var div = document.createElement('div');
       div.setAttribute('id','chart-diagram')
       parentDiv.appendChild(div);
        mygoChart = document.getElementById('chart-diagram');
        mygoChart.style.height = this.mapHeight+'px';
      //   style="background-color: white; border: solid 1px #DCDFE6; width: 100%; position:relative"
        mygoChart.style.border = 'solid 1px #DCDFE6'
         if (window.goSamples) goSamples(); // init for these samples -- you don't need to call this
         let self = this;
         let lastStroked = null
         self.myDiagram = $(go.Diagram,"chart-diagram", // must name or refer to the DIV HTML element
            {
               scale: 0.8,
               allowDelete: false,
               mouseOver:doMouseOver,
               layout: $(go.TreeLayout,{angle: 180, layerSpacing: 150}),  //angle 角度  layerSpacing 块之间的距离
               "undoManager.isEnabled": true
            }
         );
         // 设置行前图形颜色
         var colors = {
            'red': '#be4b15',
            'green': '#52ce60',
            'blue': '#6ea5f8',
            'lightred': '#fd8852',
            'lightblue': '#afd4fe',
            'lightgreen': '#b9e986',
            'pink': '#faadc1',
            'purple': '#d689ff',
            'orange': '#fdb400',
         }
         var itemTempl = $(
            go.Panel,
            "Horizontal",
            $(go.Shape,{ desiredSize: new go.Size(15, 15), strokeJoin: "round", strokeWidth: 3, stroke: null, margin: 2 },
               new go.Binding("figure", "figure"),
               new go.Binding("fill", "color"),
               new go.Binding("stroke", "color")
            ),
            $(go.TextBlock,{
                  font: "15px sans-serif",
                  margin: new go.Margin(5, 0)
               },
               new go.Binding("text", "name")
            ),
            new go.Binding("figure", "figure")
         );

         self.myDiagram.nodeTemplate = $(
            go.Node,
            "Auto", // the whole node panel
            {
               layoutConditions:
               go.Part.LayoutStandard & ~go.Part.LayoutNodeSized,
               fromSpot: go.Spot.AllSides,
               toSpot: go.Spot.AllSides,
               isShadowed: false,  // 显示阴影
               shadowOffset: new go.Point(3, 3),
               shadowColor: "#C5C1AA",
               cursor: "pointer",
               doubleClick: dodoubleClick,
               selectionChanged: nodeSelectionChanged,
            },
            new go.Binding("location", "location").makeTwoWay(),
            new go.Binding("desiredSize", "visible", function(v) {return new go.Size(NaN, NaN);}).ofObject("LIST"),
            $(go.Shape, "RoundedRectangle", {
               fill: "white",
               stroke: "#909399",  // 边框颜色
               strokeWidth: 1
            }),
            $( go.Panel, "Table", { stretch: go.GraphObject.Fill },
               $(go.RowColumnDefinition, {
                     row: 0,
                     sizing: go.RowColumnDefinition.None,
                     alignment: go.Spot.Left
                  },
                  new go.Binding("background", "color")
               ),
               $(
                  go.TextBlock,
                  {
                     row: 0,
                     alignment: go.Spot.Center,
                     margin: new go.Margin(5, 2, 0, 0),
                     font: "bold 16px sans-serif"
                  },
                  new go.Binding("text", "key")
               ),
               // header checkbox
               // the list of Panels, each showing an attribute
               $( go.Panel, "Vertical",
                     {
                     name: "LIST",
                     row: 1,
                     padding: 10,
                     alignment: go.Spot.TopLeft,
                     defaultAlignment: go.Spot.Left,
                     stretch: go.GraphObject.Horizontal,
                     itemTemplate: itemTempl
                  },
                  new go.Binding("itemArray", "items")
               )
            ) // end Table Panel
         ); // end Node
         self.myDiagram.linkTemplate = $(
            go.Link, // the whole link panel
            {
               selectionAdorned: true,
               layerName: "Foreground",
               reshapable: true,
               routing: go.Link.AvoidsNodes,
               corner: 0,
               curve: go.Link.JumpOver
            },
            $(
               go.Shape, // the link shape
               { stroke: "#303B45", strokeWidth: 1 }
            ),
            $(
               go.TextBlock, // the "from" label
               {
                  textAlign: "center",
                  font: "14px Helvetica, Microsoft YaHei, 微软雅黑, Arial, sans-serif",
                  stroke: "#1967B3",
                  segmentIndex: 0,
                  segmentOffset: new go.Point(NaN, NaN),
                  segmentOrientation: go.Link.OrientUpright45
               },
               new go.Binding("text", "text")
            ),
            $(
               go.TextBlock, // the "to" label
               {
                  textAlign: "center",
                  font: "14px Helvetica, Microsoft YaHei, 微软雅黑, Arial, sans-serif",
                  stroke: "#1967B3",
                  segmentIndex: -1,
                  segmentOffset: new go.Point(NaN, NaN),
                  segmentOrientation: go.Link.OrientUpright45
               },
               new go.Binding("text", "toText")
            )
         );
         self.myDiagram.addDiagramListener("ObjectSingleClicked", function(e) {
            if (e.subject.click == null) {
               return;
            }
            if (self.Select_Port.includes(e.subject.part.data.id)) {
               var idx = self.Select_Port.indexOf(e.subject.part.data.id);
               self.Select_Port.splice(idx, 1);
            } else {
               self.Select_Port.push(e.subject.part.data.id);
            }
         });
         // create the model for the E-R diagram
         var nodeDataArray = this.propsMap;
         var linkDataArray  =this.linkDataArray
         var modelData = []
         var num=0
         // 将数据和线及实例
         self.myDiagram.model = $(go.GraphLinksModel, {
            copiesArrays: true,
            copiesArrayObjects: true,
            nodeDataArray: nodeDataArray,
            linkDataArray: linkDataArray,
            "Changed": function(e) {
               if(modelData.length==0) {
                  modelData = self.myDiagram.model.Gc
               }
               if(e.ff =="choice1"){
                  var choice1List = []
                  for(var i=0;i<modelData.length;i++){
                     if(modelData[i].choice1){
                        choice1List.push(modelData[i])
                     }
                  }
                  self.selectList = choice1List
               }
            },
         });
         // 事件方法 1双击进入详情也
         function nodeSelectionChanged(node){
         }
         function dodoubleClick(e) {
            // self.$router.push("/DMS/dataMap/mapDirectory/details");
            var doc = e.documentPoint;
            var list = self.myDiagram.findObjectsNear(doc, 100, null, function(x) {
               return x instanceof go.Node;
            });
         }
         function doMouseOver(e) {
            if (e === undefined) e = self.myDiagram.lastInput;
            var doc = e.documentPoint;
            // find all Nodes that are within 100 units
            var list = self.myDiagram.findObjectsNear(doc, 100, null, function(
               x
            ) {
               return x instanceof go.Node;
            });
         }
          function doMouseOver(e){
            if (e === undefined) e = myDiagram.lastInput;
            var doc = e.documentPoint;
            // find all Nodes that are within 100 units
            var list = self.myDiagram.findObjectsNear(doc, 20, null, function(x) { return x instanceof go.Node; });
            var closest = null;
            var closestDist = 999999999;
            list.each(function(node) {
               var dist = doc.distanceSquaredPoint(node.getDocumentPoint(go.Spot.Center));
               if (dist < closestDist) {
               closestDist = dist;
               closest = node;
               }
            })
            showToolTip(closest, self.myDiagram);
         }
         function showToolTip(obj, diagram){
            if (obj !== null) {
               var node = obj.part;
               var e = diagram.lastInput;
               var shape = node.findObject("SHAPE");
               if (lastStroked !== null && lastStroked !== shape) lastStroked.stroke = null;
               lastStroked = shape;
               updateInfoBox(e.viewPoint, node.data);
            } else {
               if (lastStroked !== null) lastStroked.stroke = null;
               lastStroked = null;
               document.getElementById("infoBoxHolder").innerHTML = "";
            }
         }
         // 更新hover 内容
         function updateInfoBox(mousePt, data) {
            var box = document.getElementById("infoBoxHolder");
            box.innerHTML = "";
            var infobox = document.createElement("div");
            infobox.id = "infoBox";
            box.appendChild(infobox);
            var child = document.createElement("div");
            child.className = "chart-diagram-info-content"; child.textContent ="表描述："+(data.comment?data.comment:'暂无描述')
            infobox.appendChild(child);
            box.style.left = mousePt.x + "px";
            box.style.top = mousePt.y  + "px";
            box.style.position="absolute"
            box.style.zIndex=9999999999
         }
      },
      selectMap(type){
           if(type =='申请'){
             if(this.selectList.length == 0){
               this.$message({
                        message: '请选择数据列表中的数据才能进行权限申请',
                        type: 'error'
                  })
                  return false;
               }
               sessionStorage.setItem("selectList",JSON.stringify(this.selectList))
               this.$router.push("/DMS/dataMap/mapDirectory/mapPermis?dirId="+this.selectList[0].dirId);
            } else if(type =='更新'){
               this.getTableMapList()
            } else {
                if(!this.selectList.length) {
                  this.$message({
                     message: '请选择数据列表中的数据才能进行复制',
                     type: 'error'
                  })
                  return false;
               }
               sessionStorage.setItem("selectList",JSON.stringify(this.selectList))
               this.$router.push("/DMS/dataMap/mapDirectory/mapCopy?dirId="+this.selectList[0].dirId);
            }
      },
      magnifyHanle(){
           // 放大
         this.myDiagram.commandHandler.increaseZoom()
      },
      decreaseHandle(){
         // 缩小
          this.myDiagram.commandHandler.decreaseZoom();
      }
   }
};
</script>
